/**
 * 
 */
package com.edocbase.desktop.plugins.control;

import java.util.List;

import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.OpenWindowListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.StatusTextEvent;
import org.eclipse.swt.browser.StatusTextListener;
import org.eclipse.swt.browser.VisibilityWindowListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.widgets.Widget;

import com.edocbase.desktop.lightweight.widgets.TabItem;
import com.edocbase.desktop.plugins.mdiary.ButtonComposite;
import com.edocbase.desktop.plugins.mdiary.MDiaryActionConstants.MDairyActionID;
import com.edocbase.desktop.plugins.mdiary.MDiaryUI;
import com.edocbase.desktop.plugins.mdiary.ToolButtonManager;
import com.edocbase.desktop.swt.widgets.RichBrowser;

/**
 * @author X61
 * 
 */
class BrowserOpenListener implements OpenWindowListener, LocationListener,
		VisibilityWindowListener, StatusTextListener, ProgressListener {
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger
		.getLogger(BrowserOpenListener.class);
	private MDiaryUI diaryUI = null;
	private HTMLRichViewer richViewer = null;

	public BrowserOpenListener(MDiaryUI diaryUI, HTMLRichViewer htmlViewer) {
		super();
		this.diaryUI = diaryUI;
		this.richViewer = htmlViewer;
		RichBrowser richBrowser = this.richViewer.getRichBrowser();
		
		richBrowser.addStatusTextListener(this);
		richBrowser.addProgressListener(this);
		richBrowser.addLocationListener(this);
		richBrowser.addOpenWindowListener(this);
		richBrowser.addVisibilityWindowListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.swt.browser.OpenWindowListener#open(org.eclipse.swt.browser
	 * .WindowEvent)
	 */
	@Override
	public void open(WindowEvent event) {
//		Browser oldBrowser = (Browser) event.widget;
//		RichBrowserTabItem richItem = diaryUI.openURL(null, true);
//		richItem.getBody();
//		HTMLRichViewer rviewer = richItem.htmlViewer;
//		final RichBrowser browser = rviewer.getRichBrowser();
//		event.browser = browser.getBrowser();
//		event.display.asyncExec(new Runnable() {   
//            public void run() {   
//              String url = browser.getUrl();   
//              if (logger.isDebugEnabled()) {
//				logger.debug("open .... " + url);
//			}
//            }
//		});
	}

	@Override
	public void changed(LocationEvent event) {
		Widget widget = event.widget;
		Browser browser = (Browser) widget;
		
		ToolButtonManager btnManager = diaryUI.getToolManager();
		ButtonComposite btnC = btnManager.getButton(MDairyActionID.browser_backward_action.name());
		btnC.setEnabled(browser.isBackEnabled());
		btnC = btnManager.getButton(MDairyActionID.browser_forward_action.name());
		btnC.setEnabled(browser.isForwardEnabled());
		if (logger.isDebugEnabled()) {
			logger.debug("changed......"+event.location);
		}
		
	}

	@Override
	public void changing(LocationEvent event) {
		boolean opened = true;
		String url = event.location;
		TabItem item = richViewer.getItem();
		if (logger.isDebugEnabled()) {
			logger.debug("changing " + item + "\t"+url);
		}
		if (url.equals("about:blank")){
			event.doit=false;
			return;
		}
		if (item == null) {
			return;
		}

		Widget widget = event.widget;
		Browser browser = (Browser) widget;
//		if (browser instanceof RichBrowser){
//			RichBrowser rb = (RichBrowser)browser;
//			if (rb.getReadyState() != RichBrowser.READYSTATE_COMPLETE){
//				return;
//			}
//		}
		RichBrowserTabItem tabItem = null;
		boolean needActive = false;
		List<TabItem> items = diaryUI.getWorkBody().getItems();
		for (TabItem titem : items) {
			if (titem instanceof RichBrowserTabItem) {
				RichBrowserTabItem richItem = (RichBrowserTabItem) titem;
				if (richItem.getUrl().equals(url)) {
					tabItem = richItem;
					needActive = true;
					break;
				}
			}
		}
		if (needActive) {
			diaryUI.getWorkBody().selectTab(tabItem);
			event.doit = false;
			return;
		}

//		String type = item.getItemType();
//		if (type.equalsIgnoreCase(MDiaryActionConstants.HTML_ITEM_TYPE)) {
//			// HTMLRichTabItem htmlItem = (HTMLRichTabItem)item;
//			String url2 = richViewer.getRichBrowser().getUrl();
//			if (url2.length() > 1) {
//				if (!url.equals(url2)) {
//					opened = false;
//				}
//			}
//		}
		if (!opened) {
			url = event.location;
			//RichBrowserTabItem richItem = diaryUI.openURL(url, false);
			//richItem.getBody();
		}
		event.doit = opened;
	}

	@Override
	public void hide(WindowEvent event) {

	}

	@Override
	public void show(WindowEvent event) {
		Browser oldBrowser = (Browser) event.widget;
		Browser newBrowser = (Browser)event.browser;
		String url = oldBrowser.getUrl();
		String newUrl = "";
		if (newBrowser != null){
			newUrl = newBrowser.getUrl();
		}
		//System.out.println("show......" + event.browser.getUrl());
		Browser browser = (Browser)event.widget;
	      /* popup blocker - ignore windows with no style */
	      if (!event.addressBar && !event.menuBar && !event.statusBar && !event.toolBar) {
	       // System.out.println("===>>>> Popup blocked."+(richViewer.getRichBrowser() == newBrowser));
	        event.display.asyncExec(new Runnable() {
	          public void run() {
	          
	          }
	        });
	        return;
	      }
		
	}

	@Override
	public void changed(StatusTextEvent event) {
		String msg = event.text;
	//	DesktopWindow.getWindow().setStatus(msg);
	}

	@Override
	public void changed(ProgressEvent event) {
		int total = event.total;
		int current = event.current;
		//diaryUI.getDesktopShell().getStatusbar().getJobBar().changed(total, current);
	}

	@Override
	public void completed(ProgressEvent event) {
		int total = event.total;
		int current = event.current;
		//diaryUI.getDesktopShell().getStatusbar().getJobBar().changed(total, current);
	}

}
